package kycadminrepo

import (
	"context"
	"strconv"

	"git.bybit.com/svc/dbstructure_user/pkg/o_member_jumio_record"
	"git.bybit.com/svc/go/pkg/bdal/bqb"
	"git.bybit.com/svc/go/pkg/bzap"
	"go.uber.org/zap"
)

// GetJumioWrkFlwID 通过 UID 获取最新一条 jumio 账户ID和 workflow_execution_id
func (r *repo) GetJumioWrkFlwID(ctx context.Context, memberID int64) (string, string, error) {
	var record *o_member_jumio_record.Record

	pool, err := r.userDB.DBDefaultReplicaNodePool(ctx)
	if err != nil {
		bzap.LogError(r.logger.With(zap.Int64("memberID", memberID)), "GetJumioWrkFlwID DB error", err)

		return "", "", err
	}

	idpSQL := o_member_jumio_record.Select().WhereC(func(wb *bqb.WhereBuilder) {
		o_member_jumio_record.FldMemberId.EQ(wb)
	}).OrderByC(o_member_jumio_record.FldId, bqb.DESC).LimitC(1).SQL()

	record, err = o_member_jumio_record.ScanRecordNil(idpSQL.QueryArgs(ctx, pool, bqb.Args{
		o_member_jumio_record.FldMemberId.Param(): memberID,
	}))
	if err != nil {
		return "", "", err
	}
	if record == nil {
		return "", "", nil
	}

	return record.AccountId, record.DataId, nil
}

// GetLatestL1WrkFlwID 通过 UID 获取最新一条 Jumio L1 账户ID和 workflow_execution_id
func (r *repo) GetLatestL1WrkFlwID(ctx context.Context, memberID int64) (string, string, string, error) {
	var record *o_member_jumio_record.Record

	pool, err := r.userDB.DBDefaultReplicaNodePool(ctx)
	if err != nil {
		bzap.LogError(r.logger.With(zap.Int64("memberID", memberID)), "GetJumioWrkFlwID DB error", err)

		return "", "", "", err
	}

	idpSQL := o_member_jumio_record.Select().WhereC(func(wb *bqb.WhereBuilder) {
		o_member_jumio_record.FldMemberId.EQ(wb)
		o_member_jumio_record.FldType.EQ(wb)
	}).OrderByC(o_member_jumio_record.FldId, bqb.DESC).LimitC(1).SQL()

	record, err = o_member_jumio_record.ScanRecordNil(idpSQL.QueryArgs(ctx, pool, bqb.Args{
		o_member_jumio_record.FldMemberId.Param(): memberID,
		o_member_jumio_record.FldType.Param():     1,
	}))
	if err != nil {
		return "", "", "", err
	}
	if record == nil {
		return "", "", "", nil
	}

	return record.AccountId, record.DataId, strconv.FormatInt(record.UpdatedAt.Unix(), 10) + ".000", nil
}
